package com.scs.application.modules.upms.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.utils.JwtUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.upms.entity.OnlineUser;
import com.scs.application.modules.upms.mapper.OnlineUserMapper;
import com.scs.application.modules.upms.service.LogoutService;
import com.scs.application.modules.upms.service.OnlineUserService;
import com.scs.application.modules.upms.service.UserWxService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 */
@Slf4j
@AllArgsConstructor
@Service
public class LogoutServiceImpl implements LogoutService, InitializingBean {

    private final OnlineUserMapper onlineUserMapper;

    @Autowired
    private OnlineUserService onlineUserService;


    @Autowired
    @Lazy
    private UserWxService userWxService;


    @Override
    public void logout(String token,boolean isUnBindVx) {
        OnlineUser userToken = onlineUserService.findByToken(token);
        if (userToken != null) {
            onlineUserMapper.delete(Wrappers.<OnlineUser>query().eq("jti", userToken.getJti()).or().lt("expire_time", new Date()));

            // 需要解绑，不然会一直自动登录
            if (isUnBindVx) {
                if (StringUtils.isNotBlank(userToken.getOpenId())) {
                    userWxService.unbind(userToken.getLoginKey(),userToken.getOpenId());
                }
            }

            JwtUtils.removeTokenByJti(userToken.getJti());
        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        Thread thread = new Thread(this::run);
        thread.setDaemon(true);
        thread.setName("Scheduler-DeleteExpiredOnlineUser");
    }

    private void run() {
        while (true) {
            onlineUserMapper.delete(Wrappers.<OnlineUser>query().lt("expire_time", new Date()));
            try {
                TimeUnit.MINUTES.sleep(5);
            } catch (InterruptedException e) {
                log.error("在线用户删除出错", e);
                break;
            }
        }
    }
}
